package com.example.rpcdemo.core.codec;

import com.example.rpcdemo.core.protocol.RpcRequest;
import com.example.rpcdemo.core.protocol.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class RpcEncoder extends MessageToByteEncoder<Object> {
    
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        
        try {
            oos.writeObject(msg);
            byte[] data = bos.toByteArray();
            out.writeInt(data.length);
            out.writeBytes(data);
        } finally {
            oos.close();
            bos.close();
        }
    }
}